package com.mz.ozy.activity.c2c;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.mz.ozy.R;
import com.mz.ozy.adapter.BannerPagerAdapter;
import com.mz.ozy.base.BaseActivity;
import com.mz.ozy.bean.SellOutBean;
import com.mz.ozy.bean.TransferBean;
import com.mz.ozy.mvp.presenter.SellOutPresenter;
import com.mz.ozy.mvp.view.SellOutContract;
import com.mz.ozy.utils.AppUtils;
import com.mz.ozy.utils.StringUtils;
import com.mz.ozy.utils.ToastUtils;
import com.mz.ozy.utils.Utils;
import com.mz.ozy.widget.ZoomPageTransformer;
import com.mz.ozy.widget.dialog.PayPasswordDialog;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;

import java.util.ArrayList;
import java.util.List;

import androidx.viewpager.widget.ViewPager;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SellOutActivity extends BaseActivity<SellOutContract.View, SellOutPresenter> implements SellOutContract.View, ViewPager.OnPageChangeListener {
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.tv_kt)
    TextView tvKt;
    @BindView(R.id.view_kt)
    View viewKt;
    @BindView(R.id.tv_gqjf)
    TextView tvGqjf;
    @BindView(R.id.view_gqjf)
    View viewGqjf;
    @BindView(R.id.et_buy_num)
    EditText etBuyNum;
    @BindView(R.id.tv_market_price)
    TextView tvMarketPrice;
    @BindView(R.id.tv_floating_ratio)
    TextView tvFloatingRatio;
    @BindView(R.id.tv_sell_price)
    TextView tvSellPrice;
    @BindView(R.id.tv_fee)
    TextView tvFee;
    @BindView(R.id.progress_bar_h)
    SeekBar mSeekBar;

    private List<TransferBean.BalancemapBean> urlList1 = new ArrayList<>();
    private BannerPagerAdapter mPagerAdapter;
    private String type = "1";
    private double floatRadio = 0.00;
    private double marketPrice;
    private SellOutBean sellOutBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sell_out);
        ButterKnife.bind(this);
        initTitle();
        QMUIStatusBarHelper.translucent(this);
        tvCenterTitle.setText("卖出 ");
        setTitleBarMargin();
        initViewPager();
        initView();
        mPresenter.geAssetsInfo(this, type);
    }

    private void initView() {
        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
                final int curProgress = progress - 50;
                tvFloatingRatio.setText(curProgress + "%");
                floatRadio = ((double) curProgress) / 100;
                setSellPrice();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        etBuyNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                final String buynum = etBuyNum.getText().toString().trim();
                setFee(buynum);
            }
        });
    }

    /**
     * 设置沉浸式状态栏时，要把标题栏往下移动状态栏的高度
     */
    protected void setTitleBarMargin() {
        int length = AppUtils.getStatusBarHeight(this);
        //注意布局是哪种Layout
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(titleBar.getLayoutParams());
        lp.setMargins(0, length, 0, 0);
        titleBar.setLayoutParams(lp);
    }

    private void initViewPager() {
        urlList1.add(new TransferBean.BalancemapBean());
        urlList1.add(new TransferBean.BalancemapBean());
//        mPagerAdapter = new BannerPagerAdapter(urlList1, this, 0);
        viewPager.setAdapter(mPagerAdapter);

        viewPager.setPageTransformer(true, new ZoomPageTransformer());
        viewPager.setOffscreenPageLimit(urlList1.size());//设置预加载的数量，这里设置了2,会预加载中心item左边两个Item和右边两个Item
        viewPager.addOnPageChangeListener(this);
    }

    @OnClick({R.id.back, R.id.line_kt, R.id.line_gqjf, R.id.bt_confirm, R.id.iv_delete, R.id.iv_add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.line_kt:
                viewPager.setCurrentItem(0);
                break;
            case R.id.line_gqjf:
                viewPager.setCurrentItem(1);
                break;
            case R.id.iv_delete:
                mSeekBar.setProgress(mSeekBar.getProgress() - 1);
                break;
            case R.id.iv_add:
                mSeekBar.setProgress(mSeekBar.getProgress() + 1);
                break;
            case R.id.bt_confirm:
                final String sellNum = etBuyNum.getText().toString().trim();
                if (TextUtils.isEmpty(sellNum)) {
                    ToastUtils.showToast("请输入卖出数量");
                    return;
                }
                showSportsHarmDialog();
                break;
        }
    }

    private void showSportsHarmDialog() {
        PayPasswordDialog mSportsHarmDialog = new PayPasswordDialog(this);
        mSportsHarmDialog.setOnDialogListener(new PayPasswordDialog.onDialogListener() {
            @Override
            public void onSubmit(String msg) {
                submitPayOrder(msg);
                mSportsHarmDialog.toggleDialog();
            }

            @Override
            public void onCancel() {
                mSportsHarmDialog.toggleDialog();
            }
        });
        mSportsHarmDialog.toggleDialog();
    }

    private void submitPayOrder(String pass) {
        final String sellNum = etBuyNum.getText().toString().trim();
        mPresenter.submit(SellOutActivity.this, type, sellNum, pass, String.valueOf(floatRadio));
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        if (position == 0) {
            type = "1";
            etBuyNum.setText("");
            viewKt.setVisibility(View.VISIBLE);
            viewGqjf.setVisibility(View.INVISIBLE);
            mPresenter.geAssetsInfo(this, type);
        } else if (position == 1) {
            type = "2";
            etBuyNum.setText("");
            viewKt.setVisibility(View.INVISIBLE);
            viewGqjf.setVisibility(View.VISIBLE);
            mPresenter.geAssetsInfo(this, type);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void geAssetsInfoSuccess(SellOutBean bean) {
        sellOutBean = bean;
        etBuyNum.setHint("请输入数量, 大于" + bean.getLowNum());
        tvMarketPrice.setText(StringUtils.formattingDecimal(bean.getPrice(), 2) + " CNY");
        marketPrice = Double.parseDouble(bean.getPrice());
        setSellPrice();
        final String buyNum = etBuyNum.getText().toString().trim();
        setFee(buyNum);
        if ("1".equals(type)) {
            final TransferBean.BalancemapBean balancemapBean = urlList1.get(0);
            balancemapBean.setBalance(bean.getBanlance());
//            mPagerAdapter.setCurPosition(0);
        } else {
            final TransferBean.BalancemapBean balancemapBean = urlList1.get(1);
            balancemapBean.setBalance(bean.getBanlance());
//            mPagerAdapter.setCurPosition(1);
        }
        mPagerAdapter.notifyDataSetChanged();
    }

    @Override
    public void submitSuccess(SellOutBean bean) {
        ToastUtils.showToast("卖出成功");
       // startActivity(new Intent(this, MySellKtActivity.class));
    }

    private void setFee(String buyNum) {
        if (TextUtils.isEmpty(buyNum)) {
            if (sellOutBean != null && !TextUtils.isEmpty(sellOutBean.getFixedFee())) {
                tvFee.setText(sellOutBean.getFixedFee());
            }
        } else {
            final double dbuyNum = Double.parseDouble(buyNum);
            final double dserviceBase = Double.parseDouble(sellOutBean.getServiceBase());
            if (dbuyNum > dserviceBase) {
                final double feeRate = Double.parseDouble(sellOutBean.getFeeRate());
                final double totalFee = dbuyNum * feeRate;
                tvFee.setText(Utils.subTwoNumber(totalFee));
            } else {
                tvFee.setText(sellOutBean.getFixedFee());
            }
        }
    }

    private void setSellPrice() {
        final double sellPrice = marketPrice + marketPrice * floatRadio;
        tvSellPrice.setText(Utils.subTwoNumber(sellPrice) + " CNY");
    }
}
